package utils;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import dbhelper.Comments;
import dbhelper.Items;
import entities.Comment;

public class CommentsHelper {

private static String[] SupportedTags = {
	  "&lt;a href&gt;", "&lt;/a&gt;",
	  "&lt;b&gt;", "&lt;/b&gt;",
	  "&lt;i&gt;", "&lt;/i&gt;",
	  "&lt;u&gt;", "ss&lt;/u&gt;"	
};
private static HashMap<String,String> SupportedTagsHash;

static {
	SupportedTagsHash = new HashMap<String,String>();
	for(String supportedTag : SupportedTags){
		SupportedTagsHash.put(supportedTag, 
				StringEscapeUtils.unescapeHtml4(supportedTag)
				);
	}
}

/**
 * post a new comment
 * @param comment
 * @return whether the operation was successful or not
 */
public static boolean postComment(Comment comment){
	if(comment != null && StringUtils.isNotBlank(comment.getText()) && 
			Items.isForSaleItemStringQuery(comment.getItemID())
			){
		String escapedString = escapeHTML(comment.getText());
		if(!escapedString.isEmpty()){
		comment.setText(escapedString);
		comment.setDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		return Comments.postNewComment(comment);
	}
	}
	return false;
}

/**
 * return the the comment of the specified item 
 * @param itemID
 * @param pageNumber
 * @param startFrom the date to show result after (could be null)

 * @return
 */
public static List<Comment> getComments(long itemID,Timestamp startFrom, int pageNumber){
	if(pageNumber < 0) 
		pageNumber = 0;
	return (itemID != -1) ? 
			Comments.getComments(itemID,startFrom, pageNumber) : null;
}

//filters the html in the text except the supported tags
private static String escapeHTML(String text){
	String escapedSTR = StringEscapeUtils.escapeHtml4(text);
	for(String supported : SupportedTags){
		String unEscaped = SupportedTagsHash.get(supported);
		escapedSTR = escapedSTR.replace(supported, unEscaped);
	}
	return escapedSTR;
}
	
}
